package sample;

import com.jfoenix.controls.JFXButton;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCombination;
import sample.model.Result;
import sample.model.User;
import sample.util.HttpClientUtils;
import sample.util.Utils;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller  implements Initializable{


    public JFXButton log;
    private Main application;
    public TextField laminae;
    public PasswordField passwordField;

    void setApplication(Main application){
        this.application =application;
    }

    @FXML
    public void register(){
        String loginname = laminae.getText();
        String pwd = passwordField.getText();
        Alert alert;
        if(loginname.equals("")|| pwd.equals("")){
            alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("帐号和密码都不能为空!");
        }else {
            User user = new User(loginname,pwd);
//            user.setRole(1);
            String s = Utils.userToJsonString(user);
            Result result = HttpClientUtils.sendPostHttp(Url.USER_REGISTER, s);
            String code = result.getCode();
            if (code.equals("200")) {
                alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setContentText("注册成功!请重新登录!");
            } else {
                alert = new Alert(Alert.AlertType.ERROR);
                alert.setContentText("注册失败!");
            }
        }
        alert.show();
    }
    public void login() throws Exception {
        String name = laminae.getText();
        String pwd = passwordField.getText();
        Result result = HttpClientUtils.sendGetHttp(Url.USER_LOGIN + name + "/" + pwd);
        String code = result.getCode();
        if(code.equals("200")){
            application.mainPage("user");
        }else if(code.equals("404")){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setContentText("帐号或者密码错误,请重试!");
            alert.show();
        }else if(code.equals("500")){
            application.mainPage("manager");
        }
    }

    public void initialize(URL location, ResourceBundle resources) {
//        KeyCombination keyCombination = KeyCombination.keyCombination("enter");
//

    }
}
